/**
 * 
 */
package org.ChrisRiffle.Acme.AcmeTraverser.ActionPerformers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import org.ChrisRiffle.Acme.AcmeTraverser.AbstractActionPerformer;
import org.ChrisRiffle.Acme.AcmeTraverser.TraverserControler;



/**
 * Records the path and modified date of a file or files in a filesystem
 * extending from a directory specified by the {@link TraverserControler}
 * 
 * @author RIF
 * 
 */
public class FilePathModDatePerformer extends AbstractActionPerformer {
	
	
	private static final String CSV_OUT_FILENAME = "file_list.txt";

	private List<String> resultStringList;	


	/**
	 * Get a List to be populated with csv strings representing the path and
	 * last-modified date of each file or directory that's processed by this
	 * performer
	 * 
	 * @return list of csv result strings from processing files
	 */
	private List<String> getResultStringList() {
		if (resultStringList == null) {
			resultStringList = new ArrayList<String>();
		}
		return resultStringList;
	}

	/**
	 * Records the path and modified date of a file or files in a filesystem
	 * extending from a directory specified by the {@link TraverserControler}
	 * 
	 * @see org.ChrisRiffle.Acme.AcmeTraverser.ActionPerformer#doAction(java.io.File)
	 */
	@Override
	public void doAction(File pFile) {

		if (pFile == null || pFile.isDirectory() || !pFile.isFile()) {

			//ignore, we're only interested in actual Files on disk
			return;
		}

		Date lastModDate = new Date(pFile.lastModified());

		String pFilePath = pFile.getPath();
	
		String csvLine = lastModDate.toString() + "," + pFilePath;

		getResultStringList().add(csvLine);

	}

	/**
	 * Saves the processed results to a csv file in the system user directory 
	 * based on the jvm property
	 */
	@Override
	public void shutDown() {

		try {
			exportResultsToCsv();

			// free IO resources
			getBufferedWriter().close();

			Logger.getAnonymousLogger().info("Wrote results to: "
				+ getOutputFile().getCanonicalPath());

		} catch (IOException e) {

			e.printStackTrace();

			Logger.getAnonymousLogger().severe("FAILED writing results");
		}

	}

	/**
	 * Export results To a Csv file at java system user dir
	 * 
	 * @throws IOException
	 * 				if unable to export results To a Csv file
	 */
	private void exportResultsToCsv() throws IOException {

		for (String iResult : getResultStringList()) {

			getBufferedWriter().write(iResult);

			getBufferedWriter().newLine();
		}
	}

	@Override
	public String getOutputFileName() {

		return CSV_OUT_FILENAME;
	}



	


}
